const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const path = require('path')
const fs = require('fs');

const defaultConfig = getDefaultConfig(__dirname);
const extensions = ['.tsx', '.ts', '.jsx', '.js', '.json'];
const sourceExt = ['.png', '.jpg', '.jpeg', '.svg'];

/**
 * Metro configuration
 * https://reactnative.dev/docs/metro
 *
 * @type {import('@react-native/metro-config').MetroConfig}
 */
const config = {
  projectRoot: path.resolve(__dirname, ''),
  resolver: {
    // 配置别名
    resolveRequest: (context, moduleName, platform) => {
      if (moduleName.startsWith('@/')) {
        // console.log('moduleName: ', moduleName)

        const basePath = path.resolve(__dirname, moduleName.replace('@/', 'src/'));

        // 如果是静态资源，单独处理
        for (const ext of sourceExt) {
          if (basePath.includes(ext)) {
            return { filePath: basePath, type: 'sourceFile' };
          }
        }

        // 如果有后缀，就无需处理，直接返回结果
        for (const ext of extensions) {
          if (basePath.includes(ext)) {
            return { filePath: basePath, type: 'sourceFile' };
          }
        }

        // 如果是文件，自动补全后缀名 @/pages/Home -> src/pages/Home.xxx
        for (const ext of extensions) {
          if (fs.existsSync(`${basePath}${ext}`)) {
            return { filePath: `${basePath}${ext}`, type: 'sourceFile' };
          }
        }

        // 如果是目录，自动补全路径和后缀 @/pages/Home -> src/pages/Home/index.xxx
        if (fs.existsSync(basePath) && fs.statSync(basePath).isDirectory()) {
          for (const ext of extensions) {
            const indexPath = path.join(basePath, `index${ext}`);
            if (fs.existsSync(indexPath)) {
              return { filePath: indexPath, type: 'sourceFile' };
            }
          }
        }
      }
      // Optionally, chain to the standard Metro resolver.
      return context.resolveRequest(context, moduleName, platform);
    },
  },
};

module.exports = mergeConfig(defaultConfig, config);
